package server;

import java.util.HashMap;
import java.util.LinkedList;


/**
 * Classe che gestisce i clients: Permette di aggiungere e rimuovere i clients dal sistema e invia a tutti i vari messaggi
 * 
 * @author Java e Le Storie Tese
 *
 */

public class ServerMediator implements IServerMediator {

	private LinkedList<IClient> clientList=new LinkedList<IClient>();
	private HashMap<String, String> nickMap=new HashMap<String, String>();
	
	/* (non-Javadoc)
	 * @see server.IMediator#addClient(server.Client)
	 */
	@Override
	public void addClient(IClient client){
		clientList.add(client);
	}
	
	/* (non-Javadoc)
	 * @see server.IMediator#rmClient(server.Client)
	 */
	@Override
	public void rmClient(IClient client){
		clientList.remove(client);
		
		
		for (IClient	c : clientList) {
			c.sendMessage("** "+nickMap.get(client.getSocket().getInetAddress().getHostAddress()).substring(1, nickMap.get(client.getSocket().getInetAddress().getHostAddress()).length())+" si è appena disconnesso! **");
		}
		this.sendMsg("-"+nickMap.get(client.getSocket().getInetAddress().getHostAddress()));
		nickMap.remove(client.getSocket().getInetAddress().getHostAddress());
	}
	
	/* (non-Javadoc)
	 * @see server.IMediator#sendMsg()
	 */
	@Override
	public void sendMsg(String msg){
		
		for (IClient c : clientList) {
			c.sendMessage(msg);
		}
	}

	@Override
	public void addNick(String host,String nick) {
		
		nickMap.put(host,nick);
		sendNick();
		
		
	}

	private void sendNick() {
		for (int i = 0; i < nickMap.size(); i++) {

			this.sendMsg(nickMap.get(clientList.get(i).getSocket().getInetAddress().getHostAddress()));	
		
		}
	}
	
	
	
	
	
}
